package com.hd.contentmonitor.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


 
public class JDBCConnection {
	
	static Connection connection= null;
 
  public static Connection connect() throws SQLException {

	 
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			System.out.println("Where is your MySQL JDBC Driver?");
			e.printStackTrace();
			throw new SQLException(e);
		}
	 
		System.out.println("MySQL JDBC Driver Registered!");
	 
		try {
			connection = DriverManager
			.getConnection("jdbc:mysql://localhost:3306/sitemonitor","root", "root");
	 
		} catch (SQLException e) {
			System.out.println("Connection Failed! Check output console");
			e.printStackTrace();
			throw e;
		}
	 
		if (connection != null) {
			System.out.println("You made it, take control your database now!");
		} else {
			System.out.println("Failed to make connection!");
		}
		
		return connection;
  }
  
  
  public static void closeConnection() throws SQLException{
	  
	  if(connection != null && !connection.isClosed()){
		  connection.close();
	  }
	  
  }
  
  /**
	 * Executes a given query.
	 * 
	 * @param query
	 *            The query to be executed.
	 * @return The result of the query. e.g. for update, it returns number of
	 *         rows updated.
	 * @throws HarleySystemException
	 *             Thrown when a SQLException occurs. It wraps a SQLException.
	 */
	public static ResultSet executeQuery(String query) throws RuntimeException {
		try {
			
			if(connection == null){
				connection = connect();
			}
			ResultSet result;
			Statement statement = connection.createStatement();
			result = statement.executeQuery(query);

			return result;
		} catch (SQLException e) {
			throw new RuntimeException(
					"System was unable to execute the query - " + query, e);
		}
	}
  
  
  
}